# -*- coding: utf-8 -*-

from spider_server.conf.config_util import ConfigUtil
from spider_server.logs.logger import Logger
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models

logger = Logger(__name__).get_log()


class TencentSMS(object):
    def __init__(self):
        self.phones = ConfigUtil().get("MESSAGE", "PHONES")

    def send_message(self, source):
        try:
            cred = credential.Credential("AKIDObXDcjZ8RTDgsnSqxoOkpeCTTDgsnSqx", "rRloa4JHzQbV7SWKrSmqdAPO6XhaDZeS")

            httpProfile = HttpProfile()

            httpProfile.endpoint = "sms.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

            req = models.SendSmsRequest()
            params = {
                "PhoneNumberSet": self.phones.split(","),
                "SmsSdkAppId": "1400609889",
                "SignName": "娜辉钧xyz",
                "TemplateId": "1236976",
                "TemplateParamSet": ["\"%s\"" % source]
            }
            req.from_json_string(json.dumps(params))

            resp = client.SendSms(req)

            if json.loads(resp.to_json_string())["SendStatusSet"][0]["Code"] == "Ok":
                logger.info("短信反送成功")
            else:
                logger.error("短信反送失败")
                logger.error(resp.to_json_string())

        except TencentCloudSDKException as err:
            logger.error(err)


if __name__ == '__main__':
    TencentSMS().send_message("111")

